﻿
/*----------------------------------------------------------------
 * 创建时间：2023/7/31 16:23:07
 * 作  者：wenlli 
 * 项  目：Minotaur.App.Core.Redis 
 * 描  述：
 *
 * ----------------------------------------------------------------
 * 修改人：
 * 时  间：
 * 修改说明：
 * 
 *----------------------------------------------------------------*/


using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using ServiceStack.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Minotaur.App.Core.Redis
{
    public class RedisClient : IRedisClient
    {
        private readonly PooledRedisClientManager? pooledRedis = null;

        public RedisClient(IConfiguration configuration)
        {
            try
            {
                RedisModel = configuration?.Get<GlobalConfigModel>()?.RedisConfig;
                if (RedisModel != null && !string.IsNullOrEmpty(RedisModel.Address))
                {
                    string[] redisHost = RedisModel.Address.Split(',');
                    if (redisHost.Any())
                    {
                        pooledRedis = new PooledRedisClientManager(redisHost, redisHost,
                           new RedisClientManagerConfig()
                           {
                               MaxWritePoolSize = RedisModel.MaxWritePoll,
                               MaxReadPoolSize = RedisModel.MaxReadPoll,
                               AutoStart = true
                           });
                    }
                }
            }
            catch
            {
            }
        }

        private RedisModel? RedisModel { get; set; }
        public void Add<T>(string key, T value, DateTime expiry)
        {
            if (value == null)
            {
                return;
            }

            if (expiry <= DateTime.Now)
            {
                Remove(key);

                return;
            }

            try
            {
                if (pooledRedis != null)
                {
                    using (var r = pooledRedis.GetClient())
                    {
                        if (r != null)
                        {
                            r.SendTimeout = 1000;
                            r.Set(key, value, expiry - DateTime.Now);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "存储", key);
            }
        }

        public void Add<T>(string key, T value, TimeSpan slidingExpiration)
        {
            if (value == null)
            {
                return;
            }

            if (slidingExpiration.TotalSeconds <= 0)
            {
                Remove(key);

                return;
            }
            try
            {
                if (pooledRedis != null)
                {
                    using (var r = pooledRedis.GetClient())
                    {
                        if (r != null)
                        {
                            r.SendTimeout = 1000;
                            r.Set(key, value, slidingExpiration);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "存储", key);
            }
        }

        public bool Exists(string key)
        {
            try
            {
                if (pooledRedis != null)
                {
                    using (var r = pooledRedis.GetClient())
                    {
                        if (r != null)
                        {
                            r.SendTimeout = 1000;
                            return r.ContainsKey(key);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "是否存在", key);
            }

            return false;
        }

        public T Get<T>(string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                return default(T);
            }

            T obj = default(T);

            try
            {
                if (pooledRedis != null)
                {
                    using (var r = pooledRedis.GetClient())
                    {
                        if (r != null)
                        {
                            r.SendTimeout = 1000;
                            obj = r.Get<T>(key);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "获取", key);
            }
            return obj;
        }

        public void Remove(string key)
        {
            try
            {
                if (pooledRedis != null)
                {
                    using (var r = pooledRedis.GetClient())
                    {
                        if (r != null)
                        {
                            r.SendTimeout = 1000;
                            r.Remove(key);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "删除", key);
            }

        }

        #region HASH类型封装
        public bool HashExists(string hashID, string hashField)
        {
            bool b = false;
            try
            {
                if (pooledRedis != null)
                {
                    using (var r = pooledRedis.GetClient())
                    {
                        if (r != null)
                        {
                            r.SendTimeout = 1000;
                            r.HashContainsEntry(hashID, hashField);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "HashExists", ex.Message);
            }
            return b;
        }

        public bool HashRemove(string hashID, string hashField)
        {

            bool b = false;
            try
            {
                if (pooledRedis != null)
                {
                    using (var r = pooledRedis.GetClient())
                    {
                        if (r != null)
                        {
                            r.SendTimeout = 1000;
                            r.RemoveEntryFromHash(hashID, hashField);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "HashRemove", ex.Message);
            }
            return b;
        }

        public bool HashAdd<T>(string hashID, string hashField, T Value)
        {

            bool b = false;
            try
            {
                if (pooledRedis != null)
                {
                    using (var r = pooledRedis.GetClient())
                    {
                        if (r != null)
                        {
                            r.SendTimeout = 1000;
                            r.SetEntryInHash(hashID, hashField, JsonConvert.SerializeObject(Value));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "HashAdd", ex.Message);
            }
            return b;
        }

        public bool HashAddNotExist<T>(string hashID, string hashField, T Value)
        {
            bool b = false;
            try
            {
                if (pooledRedis != null)
                {
                    using (var r = pooledRedis.GetClient())
                    {
                        if (r != null)
                        {
                            r.SendTimeout = 1000;
                            b = r.SetEntryInHashIfNotExists(hashID, hashField, JsonConvert.SerializeObject(Value));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "HashAddNotExist", ex.Message);
            }
            return b;
        }
        /// <summary>
        /// 获取hash集合中的某个元素
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="hashID"></param>
        /// <param name="hashField"></param>
        /// <returns></returns>
        public T HashGet<T>(string hashID, string hashField)
        {
            T res = default(T);
            try
            {
                if (pooledRedis != null)
                {
                    using (var r = pooledRedis.GetClient())
                    {
                        if (r != null)
                        {
                            r.SendTimeout = 1000;
                            string value = r.GetValueFromHash(hashID, hashField);
                            if (!string.IsNullOrEmpty(value))
                                res = JsonConvert.DeserializeObject<T>(value);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "HashGet", ex.Message);
            }
            return res;
        }

        /// <summary>
        /// 获取hash集合中的某些元素
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="hashID"></param>
        /// <param name="hashField"></param>
        /// <returns></returns>
        public List<T> HashGet<T>(string hashID, string[] hashField)
        {
            List<T> res = new List<T>();

            try
            {
                if (pooledRedis != null)
                {
                    using (var r = pooledRedis.GetClient())
                    {
                        if (r != null)
                        {
                            r.SendTimeout = 1000;
                            List<string> values = r.GetValuesFromHash(hashID, hashField);
                            if (values.Any())
                                values.ForEach(o => res.Add(JsonConvert.DeserializeObject<T>(o)));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "HashGet", ex.Message);
            }
            return res;
        }

        /// <summary>
        /// 获取所有hashid数据集的key/value数据集合 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public IDictionary<string, string> HashGetAll(string hashId)
        {
            IDictionary<string, string> res = new Dictionary<string, string>();

            try
            {
                if (pooledRedis != null)
                {
                    using (var r = pooledRedis.GetClient())
                    {
                        if (r != null)
                        {
                            r.SendTimeout = 1000;
                            res = r.GetAllEntriesFromHash(hashId);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("{0}:{1}发生异常!{2}", "cache", "HashGetAll", ex.Message);
            }
            return res;
        }
        #endregion
    }
}